package io.chain.ko.security;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.alibaba.fastjson.JSON;

import io.chain.ko.ajax.AjaxResult;
import io.chain.ko.common.Const;
import io.chain.ko.entity.TUser;
import io.chain.ko.service.JWTTokenService;
import io.chain.ko.service.UserService;


public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter{
	
	private AuthenticationManager authenticationManager;
	private JWTTokenService jwtTokenService;
	private UserService userService;

	public JWTLoginFilter(AuthenticationManager authenticationManager,JWTTokenService jwtTokenService,UserService userService) {
		super(new AntPathRequestMatcher("/login/jwt", "POST"));
		this.authenticationManager = authenticationManager;	
		this.jwtTokenService=jwtTokenService;
		this.userService=userService;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(username,password,null);
		Authentication authentication=authenticationManager.authenticate(token);
		return authentication;
	}

	@Override
	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
			Authentication authResult) throws IOException, ServletException {
		String username=authResult.getName();
		TUser tuser=userService.findByUsername(username);
		String token=jwtTokenService.makeToken(username);
		String authorization=Const.BEARER+token;
		tuser.setToken(authorization);
		tuser.setTokenTime(new Date());
		userService.updateUser(tuser);
		AjaxResult<Map<String,String>> ajaxResult=new AjaxResult<>();
		ajaxResult.setStatus(200L);
		ajaxResult.setTimestamp(new Date());
		ajaxResult.setMessage("登陆成功");
		Map<String,String> map=new HashMap<>();
		map.put(Const.AUTHORIZATION, authorization);
		ajaxResult.setData(map);
		response.setContentType("application/json");
		response.getOutputStream().write(JSON.toJSONString(ajaxResult).getBytes());
		response.flushBuffer();
	}	
	
}
